import streamlit as st
import importlib.util
import os
import sys

# 获取当前脚本所在目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# 页面配置字典
pages = {
    "Push & Pull Transformer AP Value": "APcalculator.py",
    "Cap and inductor": "ImpedanceCalculator.py",
    "Smith Chart": "smithmatch.py",
    "Snubber": "snubber.py",
    "Unit Calc": "unitCal.py",
    "Word Display": "worddis.py",
    "TO DO OR NOT TO DO": "DOORNOTTODO.py"
}

# 初始化会话状态
if 'current_page' not in st.session_state:
    st.session_state.current_page = None

# 定义页面切换函数
def change_page(page_name):
    st.session_state.current_page = page_name

# 清除缓存函数
def clear_cache():
    try:
        from streamlit.caching import clear_cache
        clear_cache()
    except ImportError:
        try:
            from streamlit.caching import _clear_cached_funcs
            _clear_cached_funcs()
        except ImportError:
            st.warning("无法清除缓存，请刷新页面")

# 加载并运行选定的页面
def load_page(page_name):
    script_name = pages[page_name]
    script_path = os.path.join(BASE_DIR, script_name)
    
    if not os.path.exists(script_path):
        st.error(f"找不到脚本文件: {script_path}")
        st.info(f"请确保 {script_name} 文件存在于 {BASE_DIR} 目录下")
        return
    
    try:
        sys.path.append(BASE_DIR)
        spec = importlib.util.spec_from_file_location(page_name, script_path)
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
    except Exception as e:
        st.error(f"加载页面时出错: {e}")
        import traceback
        st.text(traceback.format_exc())

# 设置CSS样式
st.markdown("""
<style>
div.stButton > button {
    width: 100%;
    height: 50px;
    font-size: 16px;
    margin-bottom: 10px;
}
</style>
""", unsafe_allow_html=True)

# 初始页面显示工具选择按钮
if st.session_state.current_page is None:
    # 计算需要的行数（每行最多3个按钮）
    num_pages = len(pages)
    num_rows = (num_pages + 2) // 3  # 向上取整

    # 按行创建按钮
    for row in range(num_rows):
        cols = st.columns(3)
        
        for i in range(3):
            idx = row * 3 + i
            if idx < num_pages:
                page_name = list(pages.keys())[idx]
                
                # 使用on_click参数绑定回调函数
                cols[i].button(
                    page_name, 
                    key=f"btn_{page_name}",
                    on_click=change_page,
                    args=(page_name,)
                )
            else:
                cols[i].write("")
    
    # 添加刷新按钮
    if st.button("Rerun"):
        st.experimental_rerun()
    
    st.markdown("---")
    # 显示应用信息
    st.info(
        f"Python 版本: {sys.version.split()[0]}\n\n"
        f"Streamlit 版本: {st.__version__}\n\n"
        f"Git 仓库链接: [Repo](https://gitee.com/yokay/code.git)"
    )    

# 工具页面显示
else:
    # 添加返回按钮和刷新按钮
    col1, col2 = st.columns(2)
    if col1.button("返回主页面"):
        st.session_state.current_page = None
        st.experimental_rerun()
    
    if col2.button("Rerun"):
        st.experimental_rerun()
    
    st.markdown("---")
    st.subheader(st.session_state.current_page)
    load_page(st.session_state.current_page)

# 页脚 - 第一行：版权信息在左侧
st.markdown("---")
col1, col2, col3= st.columns(3)
col1.write("Copyright © 2025 by [MYTHBIRD](https://www.mythbird.com)")
col2.write("[粤ICP备15000778号](https://beian.miit.gov.cn/)")
col3.write("[yokay@mythbird.com](mailto:yokay@mythbird.com)")

